#include "StdAfx.h"
#include "Machine.h"

static u32 FillBits[] = {0x0,0x1,0x3,0x7,0xF,0x1F,0x3F,0x7F,0xFF};

u32 longest = 0;

CWatchdog::CWatchdog(CMachine *O,u32 S,u32 Load)
{
Owner = O;
FrameCounterLoad = Load;
FrameCounter = Load;
Data = 0;
Size = S;
Enabled = 1;
}

CWatchdog::~CWatchdog()
{
message("watchdog: longest period = %d frames\n",longest);
}

void CWatchdog::Write(u32 n)
{
Data |= n;
if((Data == FillBits[Size]) /*|| (ResetFlag == 0)*/)
	Reset();
}

void CWatchdog::Reset()
{
//message("*** watchdog reset, %d frames passed\n",FrameCounterLoad-FrameCounter);
if((FrameCounterLoad - FrameCounter) > longest)
	longest = FrameCounterLoad - FrameCounter;
Data = 0;
FrameCounter = FrameCounterLoad;
}

void CWatchdog::Frame()
{
int i;

if(FrameCounter == 0 && Enabled)
	{
	message("watchdog resetting machine\n");
	for(i=0;i<MAX_CPUS;i++)
		{
		if(Owner->CPU[i])
			Owner->CPU[i]->Reset();
		}
	Reset();
	}
else
	FrameCounter--;
}

void CWatchdog::Enable()
{
Enabled = 1;
}

void CWatchdog::Disable()
{
Enabled = 0;
}
